package com.tanjun.web.config;

import com.tanjun.common.enums.err.LoginErrCode;
import com.tanjun.common.exception.BizException;
import com.tanjun.common.model.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<R> handleNullPointerException(NullPointerException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(R.fail("参数错误"));
    }

    @ExceptionHandler(BizException.class)
    public ResponseEntity<R> handleBizException(BizException ex) {
        log.error("服务异常:{}", ex.getMessage(), ex);
        if (ex.getErrCode()== LoginErrCode.NOT_LOGIN) { //未登录
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(R.NO_LOGIN());
        }
        if (ex.getErrCode()== LoginErrCode.NOT_PERMISSION) { //无权限
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(R.NO_PERMISSION());
        }
        if (ex.getErrCode()== LoginErrCode.NOT_ROLE) { //无权限
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(R.NO_PERMISSION());
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(R.err(ex.getCode(),ex.getMessage()));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<R> handleValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        String msg = fieldErrors.stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(";"));
        log.error("参数校验错误,{}", ex.getMessage(), ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.err(msg));
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<R> handleException(HttpMessageNotReadableException ex) {
        log.error(ex.getMessage(), ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.fail("参数错误"));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<R> handleException(Exception ex) {
        log.error(ex.getMessage(), ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.fail("服务器内部错误"));
    }
}
